import re

from django_redis import get_redis_connection
from rest_framework import serializers

from .models import User


from utils.create_token import create_token

class RegisterCreateSerializer(serializers.ModelSerializer):

    #用户再进行提交的时候有3个数据:校验密码,短信验证码,是否同意协议
    #所以,我们需要定义三个字段
    password2 = serializers.CharField(label='校验密码',allow_null=False,allow_blank=False,write_only=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,allow_null=False,allow_blank=False,write_only=True)
    allow = serializers.CharField(label='是否同意协议',allow_null=False,allow_blank=False,write_only=True)
    token = serializers.CharField(read_only=True)


    class Meta:
        model = User
        fields = ('id','token','username','password','mobile','password2','sms_code','allow')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self,value):
        if not re.match(r'1[345789]\d{9}',value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate_allow(self,value):
        #注意,前段提交的是否同意,我们已经转换为字符串
        if value != 'true':
            raise serializers.ValidationError('您未同意协议')
        return value

    def validate(self, attrs):
        # 比较密码
        password = attrs['password']
        password2 = attrs['password2']

        if password != password2:
            raise serializers.ValidationError('密码不一致')
        # 比较手机验证码
        # 获取用户提交的验证码
        code = attrs['sms_code']
        # 获取redis中的验证码
        redis_conn = get_redis_connection('code')
        # 获取手机号码
        mobile = attrs['mobile']
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码过期')

        if redis_code.decode() != code:
            raise serializers.ValidationError('验证码不正确')

        return attrs

    def create(self, validated_data):

        #删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        #
        user.save()

        #在这里生成token
        # from rest_framework_jwt.settings import api_settings
        #
        # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #
        # payload = jwt_payload_handler(user)
        # token = jwt_encode_handler(payload)
        token = create_token(user)

        user.token = token

        return user


class UserCenterInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id','username','email','mobile','email_active']

class EmailUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }



from .models import Address
class AddressesCreateSerializer(serializers.ModelSerializer):

    # 序列化的时候使用
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    #反序列化的时候使用
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):

        # validated_data
        # 没有user

        user = self.context['request'].user

        validated_data['user']=user

        user = super().create(validated_data)

        return user


    # def update(self, address, validated_data):
    #
    #
    #
    #     # address.receiver  province  city  district
    #     # place mobile  tel  email
    #     address.receiver = validated_data.get('receiver',address.receiver)
    #
    #     address.province_id = validated_data.get('province_id',address.province_id)
    #     address.city_id = validated_data.get('city_id',address.city_id)
    #     address.district_id = validated_data.get('district_id',address.district_id)
    #     address.place = validated_data.get('place',address.place)
    #     address.mobile = validated_data.get('mobile',address.mobile)
    #     address.tel = validated_data.get('tel',address.tel)
    #     address.email = validated_data.get('email',address.email)
    #     address.save()
    #     return address


from goods.models import SKU
class UserHistroySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品id',required=True,min_value=1)


    def validate_sku_id(self,value):

        # sku_id 判断商品id是否存在
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('添加的商品不存在')

        return value

    def create(self, validated_data):

        # 将数据保存在redis

        #1. 连接redis
        redis_conn = get_redis_connection('history')
        #2.获取sku_id,user_id
        sku_id = validated_data.get('sku_id')
        user=self.context['request'].user

        # 添加之前 先删除可能存在的这个sku_id
        redis_conn.lrem('history_%s'%user.id,0,sku_id)

        #3.保存  列表中
        redis_conn.lpush('history_%s'%user.id,sku_id)
        #4.只保留前5个
        redis_conn.ltrim('history_%s'%user.id,0,4)

        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')


#修改密码
class Updateserializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    old_password =serializers.CharField(required=True,write_only=True)
    password = serializers.CharField(required=True)
    password2 = serializers.CharField(required=True,write_only=True)



    def validate(self, attrs):
        print(attrs)
        # user = self.context['request'].user
        # id = self.get('id')
        user = self.context['request'].user
        old_password = attrs.get('old_password')

        print(old_password)

        if user is None:
            raise serializers.ValidationError('用户名不存在')

        if not user.check_password(old_password):
            raise serializers.ValidationError('原始密码错误')


        password = attrs.get('password')
        password2 = attrs.get('password2')

        if password != password2:
            raise serializers.ValidationError('两次密码输入不一致')
        return attrs



    def update(self, instance, validated_data):
        print(validated_data)
        # del validated_data['password2']
        # del validated_data['old_password']
        instance.password = validated_data.get('password',instance.password)
        instance.set_password(validated_data['password'])
        instance.save()
        return instance
